import pyvisa
import numpy as np
import time


class Keysight34461A:
    def __init__(self, dev_id):
        self.dev_id = dev_id
        self.a = pyvisa.ResourceManager().open_resource(dev_id)
        print(f'设备基本信息：{self.a.query("*IDN?")}')

    def clear_state(self):
        # 清除状态命令。清除所有寄存器组中的事件寄存器。也会清除错误队列。
        self.a.write('*CLS')

    def reset_dev(self):
        # 将仪器恢复为出厂默认状态
        self.a.write('*RST')
    def reset_id(self):
        self.a.write("READ?")

    def set_voltage(self, voltage):
        # 设置输出电压
        self.a.write(f'CONF:VOLT:DC {voltage}')
        print(f'设置输出电压为：{voltage}V')

    def dc_voltage(self, counts=1, plc=0.02):
        # 等待 测量完成并将所有可用的测量结果复制到仪器的输出缓冲区
        self.a.write(f'CONF:VOLT:DC {plc}, 0.003')
        self.a.write('VOLT:DC:RANG:AUTO ON')  # 设置电压量程自动调整
        self.a.write('TRIG:SOUR IMM')  # 设置触发源为立即触发
        self.a.write(f'SAMP:COUN {counts}')  # 设置采样次数
        voltage_str = self.a.query('READ?')[:-1]  # 读取本次测量生成的测量值
        voltage_out = [float(voltage) for voltage in voltage_str.split(',')]
        return voltage_out

    def dc_voltage_counts(self, counts=10, plc=0.02):
        # 等待 测量完成并将所有可用的测量结果复制到仪器的输出缓冲区
        self.a.write(f'CONF:VOLT:DC {plc},0.003')
        self.a.write('VOLT:DC:RANG:AUTO ON')  # 设置电压量程自动调整
        self.a.write('TRIG:SOUR BUS')  # 设置触发源为等待触发
        self.a.write(f'SAMP:COUN {counts}')  # 设置采样次数
        self.a.write('INIT')
        self.a.write('*TRG')
        time.sleep(0.1)
        voltage_str = self.a.query('FETC?')[:-1]  # 读取本次测量生成的测量值
        voltage_float = [float(vol) for vol in voltage_str.split(',')]
        print(np.mean(voltage_float))
        return np.mean(voltage_float)

    def measure_dc_current(self, wait_time=2):
        ret = self.a.query('MEAS:CURR:DC?')
        time.sleep(wait_time)
        current = float(ret.replace('\n', ''))
        return current


if __name__ == "__main__":
    #=======================Keysight 34461A=======================
    rm = pyvisa.ResourceManager()
    device = Keysight34461A('TCPIP::169.254.4.61::INSTR')
    device.set_voltage(9)  # 设置输出电压为9V
    print(f"输出保存的值：{device.reset_id()}")
    print(f'当前电压值：{device.dc_voltage()[0]}')
    print(f'当前电流值：{device.measure_dc_current()}')
    print(f'当前电压值：{device.dc_voltage_counts()}')

    #=======================